import IconFont from '@/components/IconFont';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Alert, Button, Checkbox, Col, message, Input, Row, Popconfirm } from 'antd';
import { useEffect, useState } from 'react';
import CommonTable from '@/components/CommonTable';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import { findIndex, remove, find } from 'lodash';
import InvertButton from "@/pages/OrderModule/common/components/InvertButton";

import Api from './service';

const descEl = (
	<Typography as="s1">
		选择哪个异常类型，哪个就会显示在筛选里
		<Typography as="s1" color="#999">
			(上下可拖动字段排序)
		</Typography>
	</Typography>
)

/** 维护异常类型 */
function ErrorTypeManageModal(props) {

	const { handleOk, handleCancel } = props;
	const [open, setOpen] = useState(false);
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [reasonList, setReasonList] = useState([]);
	const [checkAll, setCheckAll] = useState(false);
	const [indeterminate, setIndeterminate] = useState(false);
	const [deleteIds, setDeleteIds] = useState([]);
	const [inputVal, setInputVal] = useState();

	useEffect(() => {
		getErrorList();
		setOpen(true);
	}, [])

	//获取异常列表
	const getErrorList = async () => {
		setLoading(true);
		const { success, data } = await Api.getErrorReasonAll();
		if (success) {
			const arr = data.filter(v => v.display == 1);
			handleChangeCheckAll(arr.length, data.length);
			setReasonList(data);
		}
		setLoading(false);
	}

	//删除异常原因
	const delItem = (id) => {
		const list = [...reasonList];
		remove(list, ['id', id]);
		const arr = list.filter(v => v.display == 1);
		handleChangeCheckAll(arr.length, list.length);
		if (id > 0) {
			const list1 = [...deleteIds];
			list1.push(id);
			setDeleteIds(list1);
		}
		setReasonList(list);
		message.success('删除成功')
	}

	//新增异常
	const saveData = () => {
		if (!inputVal) {
			message.info('请输入内容!');
			return;
		}
		const index = findIndex(reasonList, ['name', inputVal]);
		if (index > -1) {
			message.info('已经存在该异常!');
			return;
		}
		const obj = {
			add: true,
			name: inputVal,
			type: 2,
			display: 1,
			id: Date.now() * -1
		}
		const list = [obj, ...reasonList];
		const arr = list.filter(v => v.display == 1);
		handleChangeCheckAll(arr.length, list.length);
		setReasonList(list);
		setInputVal();
		message.success('保存成功！');
	}

	//变更数据
	const handleChangeCheckAll = (len1, len2) => {
		if (len1 == len2) {
			setCheckAll(true);
			setIndeterminate(false);
		}
		if (len1 == 0) {
			setIndeterminate(false);
		}
		if (len1 > 0 && len1 < len2) {
			if (checkAll) {
				setCheckAll(false);
			}
			if (!indeterminate) {
				setIndeterminate(true);
			}
		}
	}

	//变更单个显示隐藏
	const changeDisplay = (e, r) => {
		const val = e.target.checked;
		const arr = [...reasonList];
		const obj = find(arr, ['id', r.id]);
		if (obj) {
			obj.display = val;
		}
		const list = arr.filter(v => v.display == 1);
		handleChangeCheckAll(list.length, arr.length);
		setReasonList(arr);
	}

	//点击全选
	const onCheckAllChange = e => {
		const val = e.target.checked;
		const arr = [...reasonList];
		if (val) {
			arr.map(v => v.display = 1);
		} else {
			arr.map(v => v.display = 0);
		}
		if (indeterminate) {
			setIndeterminate(false);
		}
		setCheckAll(val);
		setReasonList(arr);
	}

	//点击反选
	const handReverseSelect = () => {
		const arr = [...reasonList];
		let count = 0;
		arr.map(v => {
			if(v.display == 1) {
				count += 1;
				v.display = 0;
			} else {
				v.display = 1;
			}
		})
		if(count == 0) {
			setCheckAll(true);
			indeterminate && setIndeterminate(false);
		} else if(count == arr.length) {
			checkAll && setCheckAll(false);
			indeterminate && setIndeterminate(false);
		} 
		setReasonList(arr);
	};

	const onOk = async () => {
		setLoading(true);
		const { success } = await Api.batchUpdatErrorList({
			deleteIds,
			updateErrorConfigList: reasonList
		});
		setLoading(false);
		if (success) {
			setIsOk(true);
			setOpen(false);
		}
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	const columns = [
		{
			title: '异常类型',
			dataIndex: 'name',
			width: 200,
			render(text, record) {
				let delNode = null;
				if (record) {
					delNode = (
						<Popconfirm
						title="确认要删除该异常类型吗?"
						onConfirm={() => delItem(record.id)}
					>
						<Typography style={{ marginLeft: '4px', cursor: 'pointer' }} type="error">
							<IconFont type="iconshanchu" />
						</Typography>
					</Popconfirm>
					);
					return (
						<div style={{ display: 'flex', alignItems: 'center' }}>
							{text}
							{record.type == 2 && delNode}
						</div>
					);
				}
			}
		},
		{
			title: (
				<div style={{ display: 'flex', alignItems: 'center'}}>
					是否显示：<Checkbox indeterminate={indeterminate} checked={checkAll} onChange={onCheckAllChange} style={{ verticalAlign: 'bottom' }}>全选</Checkbox>
					<InvertButton onClick={handReverseSelect} />
				</div>
			),
			dataIndex: 'display',
			width: 240,
			render: (t, r) => {
				return (
					<Checkbox checked={t} onChange={(e) => changeDisplay(e, r)} />
				)
			}
		}
	]

	const TableProps = {
		data: reasonList,
		size: "small",
		columns,
		isSortData: true,
		rowKey: 'id',
		bordered: true,
		scroll: {
			y: '45vh'
		},
		onDragEnd(val) {
			setReasonList(val);
		}
	}

	return (
		<CommonModal title="维护异常类型" width="600px" open={open} onOk={onOk} onCancel={onCancel} afterClose={afterClose}>
			<Alert message={descEl} />
			<Row gutter={14} style={{ margin: '16px 0' }}>
				<Col flex="auto">
					<Input maxLength={20} showCount placeholder="请输入自定义异常" value={inputVal} onChange={e => setInputVal(e.target.value) } />
				</Col>
				<Col>
					<Button type="primary" ghost onClick={saveData}>保存</Button>
				</Col>
			</Row>
			<CommonTable {...TableProps} />
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default ErrorTypeManageModal;
